package com.ffsky.smtt;

import android.app.Application;
import android.content.Context;
import android.util.Log;

import com.tencent.smtt.export.external.TbsCoreSettings;
import com.tencent.smtt.sdk.QbSdk;

import java.util.HashMap;

public final class X5ModularLoader {
    final String TAG = "X5ModularLoader";
    private boolean x5Init = false;

    private static X5ModularLoader INSTANCE = null;

    public static final X5ModularLoader getInstance() {
        if (INSTANCE == null) {
            synchronized (X5ModularLoader.class) {
                INSTANCE = new X5ModularLoader();
            }
        }
        return INSTANCE;
    }

    public static final void unInstance() {
        if (INSTANCE != null) {
            INSTANCE.unload();
            INSTANCE = null;
        }
    }

    private X5ModularLoader() {

    }
    private boolean init = false;
    private Context context;
    public void load(Application application, HashMap tbsSettingsMap) {
        if(init){
            return;
        }
        context = application.getApplicationContext();
        Log.i(TAG, "load +++");
        if (tbsSettingsMap == null) {
            HashMap map = new HashMap();
            map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
            map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);

            map.put(TbsCoreSettings.TBS_SETTINGS_USE_PRIVATE_CLASSLOADER, true);
            QbSdk.initTbsSettings(map);
        } else {
            QbSdk.initTbsSettings(tbsSettingsMap);
        }
        try{
            QbSdk.initX5Environment(application.getApplicationContext(), new PreInitCallbackImpl());
        }catch (Exception exception){
            exception.printStackTrace();
        }
        init = true;
        Log.i(TAG, "load ---");

    }

    public void unload() {
        init = false;
        context = null;
        Log.i(TAG, "unload");
    }
    private class PreInitCallbackImpl implements QbSdk.PreInitCallback {
        @Override
        public void onCoreInitFinished() {
            Log.i(TAG, "onCoreInitFinished");
        }

        @Override
        public void onViewInitFinished(boolean b) {
            x5Init = b;
            //x5內核初始化完成的回调，为true表示x5内核加载成功
            //否则表示x5内核加载失败，会自动切换到系统内核。
            int  tbsVersion = QbSdk.getTbsVersion(context);
            Log.i(TAG, "onViewInitFinished-Result=" + b +" tbsVersion="+tbsVersion);
        }
    }
}
